package com.gitee.hermer.engine.jars.app.sdk.utils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.context.ApplicationContext;
import com.gitee.hermer.boot.jee.commons.bean.utils.BeanLocator;
import com.gitee.hermer.engine.jars.app.sdk.EngineAppClassLoader;

public class ApplicationContextUtils {
	
	protected static Map<ClassLoader, ApplicationContext> APP_CONTEXTS = new ConcurrentHashMap<ClassLoader, ApplicationContext>();
	
	

	public static ApplicationContext getApplicationContext()
	{
		if(Thread.currentThread().getContextClassLoader() instanceof EngineAppClassLoader){
			return APP_CONTEXTS.get(Thread.currentThread().getContextClassLoader());
		}
		return BeanLocator.getSpringContext();
	}
	
	public static void setApplicationContext(ApplicationContext value)
	{
		if(Thread.currentThread().getContextClassLoader() instanceof EngineAppClassLoader){
			APP_CONTEXTS.put(Thread.currentThread().getContextClassLoader(), value);
		}
	}
	
	public static void destroy(){
		if(Thread.currentThread().getContextClassLoader() instanceof EngineAppClassLoader){
			APP_CONTEXTS.remove(Thread.currentThread().getContextClassLoader());
		}
	}
	
	public static <T> T getBean(Class<T> clz){
		return getApplicationContext().getBean(clz);
	}

}
